"""代码解析节点"""

import re
from typing import Dict, List
from core.graph.chat_graph import ChatState


def parse_cairo_code(state: ChatState) -> ChatState:
    """解析Cairo代码"""
    content = state["messages"][-1]["content"]
    
    # 检测代码块
    code_blocks = re.findall(r'```(?:cairo)?\n?(.*?)```', content, re.DOTALL)
    
    # 检测Cairo关键字
    cairo_keywords = ["fn ", "struct ", "trait ", "impl ", "mod ", "contract ", "enum "]
    has_code = any(keyword in content for keyword in cairo_keywords)
    
    # 分析代码类型
    code_type = "other"
    if "fn " in content:
        code_type = "function"
    elif "struct " in content:
        code_type = "struct"
    elif "trait " in content:
        code_type = "trait"
    elif "impl " in content:
        code_type = "implementation"
    elif "mod " in content:
        code_type = "module"
    elif "contract " in content:
        code_type = "contract"
    
    # 提取函数名
    function_names = []
    if code_type == "function":
        fn_matches = re.findall(r'fn\s+(\w+)\s*\(', content)
        function_names = fn_matches
    
    # 检测错误模式
    error_patterns = [
        r'error:\s*(.+)',
        r'panic:\s*(.+)',
        r'CompilationError:\s*(.+)',
        r'RuntimeError:\s*(.+)'
    ]
    
    detected_errors = []
    for pattern in error_patterns:
        matches = re.findall(pattern, content, re.IGNORECASE)
        detected_errors.extend(matches)
    
    ctx = {
        "has_code": has_code,
        "code_type": code_type,
        "code_blocks": code_blocks,
        "function_names": function_names,
        "detected_errors": detected_errors,
        "cairo_keywords_found": [kw for kw in cairo_keywords if kw in content]
    }
    
    state["cairo_context"] = ctx
    return state
